window.onload = function() {
    layui.use(['jquery', 'layer'], function() {
        var $ = layui.jquery,
            layer = layui.layer;

        $(".getchecknum").on("click", function() {
            getCheckNum(".shop-phone", ".getchecknum");
        })
        var uploader = {
            'data': {
                'token': '',
                'uploadDomain': '',
                'domain': ''
            },
            // 'complete':function(res){
            //     var url="http://"+uploader.data.domain +"/"+ res.key;
            //     $(".pic3").attr("src",url);
            //     $(".pic3-val").val(res.key);
            // },
            'error': function() {
                console.dir(arguments);
            },
            // 分片上传时的进度展示功能在此书写.
            'next': function(response) {
                // var chunks = response.chunks || [];
                // var total = response.total;
            },
            'init': function() {
                $.ajax({
                    'url': '/upload/get-token',
                    'type': 'POST',
                    'dataType': 'json',
                    'success': function(data) {
                        if (data.code != 200) {
                            Utils.layer.msg(data.msg);
                            return false;
                        }
                        uploader.data.token = data.data.token; // token
                        uploader.data.domain = data.data.domain; // 显示域名
                        // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
                        // console.log(uploader.data.token)
                    }
                });
            },
            'eventBind': function() {
                this.init();
                $('.pic-card1').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic1', '.hidden-pic1', '.default1')
                });
                $('.pic-card2').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic2', '.hidden-pic2', '.default2')
                });
                $('.pic-card3').on('change', function(e) {
                    var fileList = e.target.files[0];
                    UpladFile(fileList, '.pic3', '.hidden-pic3', '.default3')
                });

                function UpladFile(ele, showPic, hiddenPic, deFault, index) {
                    var fileObj = ele; // js 获取文件对象
                    var formData = new FormData(); // FormData 对象
                    if (fileObj.size / 1024 > 200) { //大于200k，进行压缩上传
                        photoCompress(fileObj, { quality: 0.8 }, function(base64Codes) {
                            //console.log("压缩后：" + base.length / 1024 + " " + base);
                            var bl = convertBase64UrlToBlob(base64Codes);
                            formData.append("file", bl, "file_" + Date.parse(new Date()) + ".jpg"); // 文件对象

                            var token = uploader.data.token;
                            var config = {
                                useCdnDomain: true,
                                disableStatisticsReport: false,
                                region: qiniu.region.z0
                            };
                            var putExtra = {
                                fname: "",
                                params: {},
                                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                            };
                            // var file = this.files[0];
                            bl.name = fileObj.name;
                            var file = bl;
                            if (TestFileSuffix(file.name) < 0) {
                                Utils.layer.msg('请上传 jpg/png 类型图片');
                                return;
                            }
                            var observable;
                            if (file) {
                                // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                                var files = file;
                                var key1 = file.name;
                                var key = key1.split(".")[0] + Date.parse(new Date()) + "." + key1.split(".")[1];
                                putExtra.params["x:name"] = key.split(".")[0];
                                // 配置完成的数组.
                                // if(showPic=='.pic1'){
                                var subObject = {
                                    next: uploader.next,
                                    error: uploader.error,
                                    complete: function(res) {
                                        var url = "http://" + uploader.data.domain + "/" + res.key;
                                        $(deFault).hide();
                                        $(showPic).show().attr("src", url);
                                        $(hiddenPic).val(res.key);
                                    }
                                };
                                // }
                                var subscription;
                                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                                observable = qiniu.upload(files, key, token, putExtra, config);
                                subscription = observable.subscribe(subObject);
                                // subscription.unsubscribe();  // 取消上传.
                            }
                        });
                    } else {
                        var token = uploader.data.token;
                        var config = {
                            useCdnDomain: true,
                            disableStatisticsReport: false,
                            region: qiniu.region.z0
                        };
                        var putExtra = {
                            fname: "",
                            params: {},
                            mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
                        };
                        var file = fileObj;
                        // bl.name=fileObj.name;
                        // var file=bl;
                        if (TestFileSuffix(file.name) < 0) {
                            Utils.layer.msg('请上传 jpg/png 类型图片');
                            return;
                        }
                        var observable;
                        if (file) {
                            // var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                            var files = file;
                            var key1 = file.name;
                            var key = key1.split(".")[0] + Date.parse(new Date()) + "." + key1.split(".")[1];
                            putExtra.params["x:name"] = key.split(".")[0];
                            // 配置完成的数组.
                            // if(showPic=='.pic1'){
                            var subObject = {
                                next: uploader.next,
                                error: uploader.error,
                                complete: function(res) {
                                    var url = "http://" + uploader.data.domain + "/" + res.key;
                                    $(deFault).hide();
                                    $(showPic).show().attr("src", url);
                                    $(hiddenPic).val(res.key);
                                }
                            };
                            // }

                            var subscription;
                            // 调用sdk上传接口获得相应的observable，控制上传和暂停
                            observable = qiniu.upload(files, key, token, putExtra, config);
                            subscription = observable.subscribe(subObject);
                            // subscription.unsubscribe();  // 取消上传.
                        }
                    }
                }

                function photoCompress(file, w, objDiv) {
                    var ready = new FileReader();
                    /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
                    ready.readAsDataURL(file);
                    ready.onload = function() {
                        var re = this.result;
                        canvasDataURL(re, w, objDiv)
                    }
                }

                function canvasDataURL(path, obj, callback) {
                    var img = new Image();
                    img.src = path;
                    img.onload = function() {
                        var that = this;
                        // 默认按比例压缩
                        var w = that.width,
                            h = that.height,
                            scale = w / h;
                        w = obj.width / 1.2 || w / 1.2;
                        h = obj.height / 1.2 || (w / scale) / 1.2;
                        var quality = 0.8; // 默认图片质量为0.7
                        //生成canvas
                        var canvas = document.createElement('canvas');
                        var ctx = canvas.getContext('2d');
                        // 创建属性节点
                        var anw = document.createAttribute("width");
                        anw.nodeValue = w;
                        var anh = document.createAttribute("height");
                        anh.nodeValue = h;
                        canvas.setAttributeNode(anw);
                        canvas.setAttributeNode(anh);
                        ctx.drawImage(that, 0, 0, w, h);
                        // 图像质量
                        if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                            quality = obj.quality;
                        }
                        // quality值越小，所绘制出的图像越模糊
                        var base64 = canvas.toDataURL('image/jpeg', quality);
                        // 回调函数返回base64的值
                        callback(base64);
                    }
                }
                /**
                 * 将以base64的图片url数据转换为Blob
                 * @param urlData
                 *            用url方式表示的base64图片数据
                 */
                function convertBase64UrlToBlob(urlData) {
                    var arr = urlData.split(','),
                        mime = arr[0].match(/:(.*?);/)[1],
                        bstr = atob(arr[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    return new Blob([u8arr], { type: mime });
                }
            }
        };

        uploader.eventBind();

        function getCheckNum(phoneNum, CheckNumBtn) {
            var phone_num = $(phoneNum).val();
            if (/^[1][3,4,5,7,8][0-9]{9}$/.test(phone_num)) {
                var second = 90;
                var timer = setInterval(function() {
                    second--;
                    if (second != 0) {
                        $(CheckNumBtn).css({ "background": "#999", "color": "#eee" }).val("重新发送" + second + "s");
                        $(CheckNumBtn).attr("disabled", "disabled");
                    } else {
                        $(CheckNumBtn).val("获取验证码").css({ "background": "#08c", "color": "#fff" });
                        $(CheckNumBtn).removeAttr("disabled");
                        clearInterval(timer);
                    }
                }, 1000);
                $.post("/code/send-code", { phone: phone_num }, function success(data) {
                    if (data.code == 200) {
                        Utils.layer.msg(data.msg);
                    } else { Utils.layer.msg(data.msg); }
                })
            } else {
                Utils.layer.msg("您输入的电话有误，请重新输入")
            }
        }

        $(".add-shop").on("click", function() {
            var shopName = $(".input1").val().trim(), //店铺名称
                loginAccount = $(".input2").val().trim(), //登录账号
                loginPassword = $(".input3").val().trim(), //登录密码
                shopManageName = $(".input4").val().trim(), //店铺管理人姓名
                shopManageEmail = $(".input5").val().trim(), //店铺管理人邮箱
                shopManagePhone = $(".input6").val().trim(), //店铺管理人手机号
                checkNumber = $(".input7").val().trim(), //验证码
                shopManageIdcard = $(".input8").val().trim(), //店铺管理人身份证号
                shopManageId = $(".hidden-pic1").val().trim(), //管理人身份证正面照片
                shopManageIdReverse = $(".hidden-pic2").val().trim(), //管理人身份证反面照片
                shopManageIdHandle = $(".hidden-pic3").val().trim(), //管理人手持身份证照片
                flag = true;

            if (shopName == '') {
                Utils.layer.msg("请填写店铺名称");
                flag = false;
            } else if (loginAccount == '') {
                Utils.layer.msg("请填写登录账号");
                flag = false;
            } else if (loginPassword == '') {
                Utils.layer.msg("请填写登录密码");
                flag = false;
            } else if (shopManageName == '') {
                Utils.layer.msg("请填写店铺管理人姓名");
                flag = false;
            } else if (shopManageEmail == '') {
                Utils.layer.msg("请填写店铺管理人邮箱");
                flag = false;
            } else if (shopManagePhone == '') {
                Utils.layer.msg("请填写店铺管理人手机号");
                flag = false;
            } else if (checkNumber == '') {
                Utils.layer.msg("请填写验证码");
                flag = false;
            } else if (shopManageIdcard == '') {
                Utils.layer.msg("请填写店铺管理人身份证号");
                flag = false;
            } else if (shopManageId == '') {
                Utils.layer.msg("请上传管理人身份证正面照片");
                flag = false;
            } else if (shopManageIdReverse == '') {
                Utils.layer.msg("请上传管理人身份证反面照片");
                flag = false;
            } else if (shopManageIdHandle == '') {
                Utils.layer.msg("请上传管理人手持身份证照片");
                flag = false;
            }

            if (flag) {
                var dataStr = $(".layui-form").serialize()
                $.post("/shop/add-shop", dataStr, function(res) {
                    if (res.code == 200) {
                        Utils.layer.msg('入驻申请已提交成功，需要等待管理员审核！')
                        setTimeout(function() {
                            location.href = "/admin/login";
                        }, 1200)
                    } else {
                        Utils.layer.msg(res.msg)
                    }
                })
            }
        })
    })


}